package com.lenovo.smarttraffic.ui.activity.stage2;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import java.util.HashMap;
import java.util.Map;

public class CarTsActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar mToolbar;
    private DrawerLayout mDrawer;
    private NavigationView navigationView;

    private Button findBtn;
    private TextView account_threshold_tv;

    private Spinner car_select;

    private EditText max_et, min_et;

    private Button set_threshold_btn;

    private Button account_th_btn, speed_th_btn;

    private SharedPreferences preferences;

    private int money, carId;

    private AlertDialog dialog;


    @Override
    protected int getLayout() {
        return R.layout.activity_car_threshold;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        preferences = getSharedPreferences(Constant.ACCOUNT, MODE_PRIVATE);

        initView();
    }

    public void initView() {
        mToolbar = findViewById(R.id.toolbar_second);

        mDrawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        toggle.syncState();
        mDrawer.addDrawerListener(toggle);

        findBtn = findViewById(R.id.findBtn);
        findBtn.setOnClickListener(view -> doFind());
        account_threshold_tv = findViewById(R.id.account_threshold_tv);

        car_select = findViewById(R.id.car_select);
        car_select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {
                carId = pos + 1;
                doFind();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        max_et = findViewById(R.id.max_et);
        min_et = findViewById(R.id.min_et);

        set_threshold_btn = findViewById(R.id.set_threshold_btn);
        set_threshold_btn.setOnClickListener(view -> {
            String minStr = min_et.getText().toString();
            String maxStr = max_et.getText().toString();
            if (minStr.isEmpty() || maxStr.isEmpty()) {
                ToastUtils.showToast(this, "请输入阈值", Toast.LENGTH_SHORT);
                return;
            }

            int min = Utils.parseInt(minStr);
            int max = Utils.parseInt(maxStr);

            if (max < min) {
                ToastUtils.showToast(this, "请输入正确的阈值", Toast.LENGTH_SHORT);
                return;
            }

            Map<Object, Object> map = new HashMap<>();
            map.put(Constant.THRESHOLD_MIN, minStr);
            map.put(Constant.THRESHOLD_MAX, maxStr);

            preferences.edit().putString("car" + carId, new Gson().toJson(map)).apply();
            doFind();
            ToastUtils.showToast(this, "设置成功", Toast.LENGTH_SHORT);
        });

        account_th_btn = findViewById(R.id.account_threshold_btn);
        speed_th_btn = findViewById(R.id.speed_threshold_btn);
    }

    @Override
    protected void onResume() {
        super.onResume();

        doFind();
    }


    private void doFind() {
        Map data = new Gson().fromJson(preferences.getString("car" + carId, null), Map.class);
        if (data != null) {
            String threshold_min = (String) data.get(Constant.THRESHOLD_MIN);
            String threshold_max = (String) data.get(Constant.THRESHOLD_MAX);

            HttpUtils.post("get_car_account_balance", new HttpUtils().setParam("CarId", carId).setParam("UserName", MainActivity.userName),
                    response -> {
                        Map responseMap = new Gson().fromJson(response.toString(), Map.class);
                        if (responseMap.get("RESULT").toString().equals("S")) {
                            money = (int) Utils.parseDouble(responseMap.get("Balance").toString());
                            if (money < Utils.parseInt(threshold_min)) {
                                if (dialog == null) {
                                    dialog = new AlertDialog.Builder(this)
                                            .setTitle("提示")
                                            .setMessage("余额不足请充值")
                                            .setPositiveButton("充值", (dialogInterface, i) -> startActivity(new Intent(CarTsActivity.this, ChargeActivity.class)))
                                            .setNegativeButton("取消", null)
                                            .create();
                                    dialog.show();
                                } else if (!dialog.isShowing()) {
                                    dialog.show();
                                }
                            }
                        } else if (responseMap.get("RESULT").toString().equals("F")) {
                            Toast.makeText(this, "请求错误，可能没有这辆车", Toast.LENGTH_SHORT).show();
                        }
                    });

            account_threshold_tv.setText(String.format("阈值：最低%s元-最高%s元", threshold_min, threshold_max));
        } else {
            account_threshold_tv.setText("查询失败，请设置阈值");
        }

    }

    @Override
    public void onBackPressedSupport() {
        if (mDrawer.isDrawerOpen(GravityCompat.START)) {
            mDrawer.closeDrawer(GravityCompat.START);
        } else {
            finish();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.account_charge:
                startActivity(new Intent(this, ChargeActivity.class));
                break;
            case R.id.car_charge:
                startActivity(new Intent(this, CarChargeActivity.class));
                break;
            case R.id.account_manage:
                startActivity(new Intent(this, AccountChargeActivity.class));
                break;
            case R.id.etc_manage:
                startActivity(new Intent(this, ETCManageActivity.class));
                break;
            case R.id.etc_account:
                startActivity(new Intent(this, ETCAccountActivity.class));
                break;
        }

        mDrawer.closeDrawer(GravityCompat.START);
        return true;
    }

}
